﻿using System.Collections.Generic;
using System.Threading.Tasks;
namespace Athena.ProxyGenerator.Implementaions
{
    using Convertible;
    using ExceptionHandler;
    using Message;
    using Runtime.Client;

    public abstract class ServiceProxyAbstractClient
    {
        private readonly IRpcInvokeService _rpcInvokeService;
        private readonly ITypeConvertibleService _typeConvertibleService;


        protected ServiceProxyAbstractClient(IRpcInvokeService rpcInvokeService, ITypeConvertibleService typeConvertibleService)
        {
            _rpcInvokeService = rpcInvokeService;
            _typeConvertibleService = typeConvertibleService;
        }

        protected async Task InvokeAsync(IDictionary<string, object> arguments, string correlationId)
        {
            var rpcInvokeResultMessage = await _rpcInvokeService.InvokeAsync(new RpcInvokeContext()
            {
                InvokeMessage = new RpcInvokeMessage()
                {
                    Arguments = arguments,
                    CorrelationId = correlationId,
                }
            });
            if (rpcInvokeResultMessage != null && rpcInvokeResultMessage.Code != (int)AthenaRpcInvokeResultCodeDisplay.成功)
            {
                throw new RpcException(rpcInvokeResultMessage.Code, rpcInvokeResultMessage.Message);
            }
        }

        protected async Task<T> InvokeAsync<T>(IDictionary<string, object> arguments, string correlationId)
        {
            var rpcInvokeResultMessage = await _rpcInvokeService.InvokeAsync(new RpcInvokeContext()
            {
                InvokeMessage = new RpcInvokeMessage()
                {
                    Arguments = arguments,
                    CorrelationId = correlationId,
                }
            });
            if (rpcInvokeResultMessage == null)
            {
                return default(T);
            }
            if (rpcInvokeResultMessage.Code != (int)AthenaRpcInvokeResultCodeDisplay.成功)
            {
                throw new RpcException(rpcInvokeResultMessage.Code, rpcInvokeResultMessage.Message);
            }

            return _typeConvertibleService.Convert<T>(rpcInvokeResultMessage.Result);
        }
    }
}
